package com.zhengsr.drawbroad.state;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.MotionEvent;

import com.zhengsr.drawbroad.ActionType;
import com.zhengsr.drawbroad.data.StateData;
import com.zhengsr.drawbroad.utils.CommandUtils;

/**
 * Created by zhengshaorui
 * time: 2018/7/22
 */

public class PenAction extends BaseAction {
    private static final String TAG = "PenAction";
    private float mPreX,mPreY;
    private Path mPath ;
    private Paint mPaint;

    private PenAction( ){

        //init path and paint
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(10);
        mPaint.setColor(Color.BLUE);
        mPaint.setAntiAlias(true);
        mPaint.setDither(true); //消除拉动
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
    }

    public void setColor(int color){
        mPaint.setColor(color);
    }

    public static PenAction create(){
        return new PenAction();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                touchDown(event.getX(),event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                touchMove(event.getX(),event.getY());
                break;
            case MotionEvent.ACTION_UP:
             //   touchUp();
                break;
            default:
                break;
        }
        return false;
    }

    @Override
    public void draw(Canvas canvas) {
        canvas.drawPath(mPath,mPaint);
    }

    @Override
    public ActionType getViewType() {
        return ActionType.PEN;
    }


    /**
     * down 方法
     * @param x
     * @param y
     */
    private void touchDown(float x, float y) {
        if (mPath == null){
            mPath = new Path();
        }
        mPreX = x;
        mPreY = y;
        mPath.moveTo(x,y); //起点

    }

    /**
     *
     * @param x
     * @param y
     */
    private void touchMove(float x, float y) {

        float dx = Math.abs(x - mPreX);
        float dy = Math.abs(y - mPreY);
        if (dx >2 || dy >2){ //有移动时才画
            // 注意这里的mprex，虽然在down的时候，我们记录了mprex，但这里却是 move 的坐标
            // 所以，这里的quadto，其实是在移动时坐标的中点
            mPath.quadTo(mPreX,mPreY,(x + mPreX)/2,(y + mPreY)/2);
        }
        mPreX = x;
        mPreY = y;

    }

    private void touchUp() {
        Path cachepath = new Path(mPath);
        Paint paint = new Paint(mPaint);
        StateData data = new StateData(paint,cachepath);
        CommandUtils.getInstance().add(data);
        mPath.reset();
    }
}
